import { observable, action, computed, runInAction } from 'mobx';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import { noticeMessage } from '@utils/common-message';

class ChangePasswordStore extends BaseStore {
    @observable oldPassword;
    @observable password;
    @observable repeatPassword;
    @observable errMsg = {
        oldPassword: '',
        password: '',
        repeatPassword: '',
    };
    isSuccess = false;
    // 弹框提示的错误
    globalErrMsg = '';

    @computed
    get isSubmitBtnDisabled() {
        return !this.oldPassword || !this.password || !this.repeatPassword;
    }

    @action
    reset() {
        this.oldPassword = '';
        this.password = '';
        this.repeatPassword = '';
        this.isSuccess = false;
        this.globalErrMsg = '';
        this.errMsg = {
            oldPassword: '',
            password: '',
            repeatPassword: '',
        };
    }


    /**
     * 验证密码
     */
    @action
    validateOldPassword() {
        this.errMsg.oldPassword = '';
        if (!this.password) {
            this.errMsg.oldPassword = noticeMessage.inputFormatError('原密码');
            return false;
        }
        return true;
    }

    /**
     * 验证密码
     */
    @action
    validatePassword() {
        this.errMsg.password = '';
        if (!validationUtil.isSimplePassword(this.password)) {
            this.errMsg.password = noticeMessage.passwordFormatError();
            return false;
        }
        return true;
    }

    /**
     * 验证确认密码
     */
    @action
    validateRepeatPassword() {
        this.errMsg.repeatPassword = '';
        if (this.repeatPassword !== this.password) {
            this.errMsg.repeatPassword = noticeMessage.repeatPasswordError();
            return false;
        }
        return true;
    }

    @action
    async submit() {
        this.globalErrMsg = '';
        if (!this.validateOldPassword() || !this.validatePassword() || !this.validateRepeatPassword()) {
            return;
        }
        const res = await this.post('/user/change-password', {
            old_password: this.oldPassword,
            password: this.password,
            repeat_password: this.repeatPassword,
        }, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isSuccess = true;
            } else if (code === '1200') {
                this.errMsg.oldPassword = '原密码不正确，请重试';
            } else {
                this.globalErrMsg = res.message || '修改密码失败，请重试';
            }
        });
    }
}

export default new ChangePasswordStore();
